package com.test.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.test.dao.CarDao;
import com.test.dao.mapper.CarMapper;
import com.test.entity.Car;
import com.test.entity.Result;
import com.test.model.CarCriteria;
import com.test.service.CarService;
import com.test.utils.ResultUtil;
import com.ucar.common.utils.page.jpa.PageImpl;
import com.ucar.common.utils.page.jpa.model.PagingConditions;
import com.ucar.common.utils.page.mybatis.MyRowBounds;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import tk.mybatis.mapper.entity.Example;

@RestController
public class CarController {

	@Autowired
	private CarService carservice;

	@Autowired
	private CarDao carDao;

	@Autowired
	private CarMapper carMapper;

	@GetMapping("/jpa/page")
	@ApiOperation(value = "分页条件查询")
	public Result<PageImpl<Car>> findCarInfos(CarCriteria carCriteria, @Validated PagingConditions paging) {
		Result<PageImpl<Car>> result = new Result<PageImpl<Car>>("200", "jpa分页条件查询");
		result.setData(carservice.findCarInfosByPage(carCriteria, paging));
		return result;
	}

	@GetMapping("/mybatis/page")
	public Result<List<Car>> findAll(Car car, MyRowBounds myRowBounds) {
		return ResultUtil.success(carMapper.selectByRowBounds(car, myRowBounds));
	}

	@GetMapping("/mybatis/examplepage")
	public Result<List<Car>> findAllByExample(Car car, MyRowBounds myRowBounds) {
		Example example = new Example(Car.class);
		example.createCriteria().andAllEqualTo(car);
		return ResultUtil.success(carMapper.selectByExampleAndRowBounds(example, myRowBounds));
	}

	/**
	 * 
	 * @param car
	 * @param bindingResult
	 *            校验的信息会转载到bindingResult对象中
	 * @return
	 */
	@PostMapping("/jpa/save")
	public Result<Car> save(@Valid Car car, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultUtil.error("500", bindingResult.getFieldError().getDefaultMessage());
		}
		return ResultUtil.success(carDao.save(car));
//		return null;模拟未知异常
	}
	
	@GetMapping("/jpa/getCar/{id}")
	public Result<Car> findOne(@PathVariable @ApiParam("id") Integer id) throws Exception{
		return ResultUtil.success(carservice.findOne(id));
	}

}
